﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

public class IOUntil
{
    public static List<string> nameArray = new List<string>();
    /// <summary>
    /// 创建文本文件
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="content">文件内容</param>
    public static void CreateTextFile(string filePath,string content)
    {
        DeleteFile(filePath);
        using (FileStream fs = File.Create(filePath))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.Write(content.ToString());
            }
        }
    }

    public static void CreateTextFileAppend(string filePath, string content)
    {
        StreamWriter sw;
        FileInfo fi = new FileInfo(filePath);
        
        sw = fi.AppendText();        //直接重新写入，如果要在原文件后面追加内容，应用fi.AppendText()
        sw.WriteLine(content);
        sw.Close();
        sw.Dispose();
    }
    /// <summary>
    /// 获取文本全部内容
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string GetFileText(string filePath)
    {
        //文件路径
        
        try
        {
            if (File.Exists(filePath))
            {
                using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
                {
                    string Text = sr.ReadToEnd();
                    byte[] mybyte = Encoding.UTF8.GetBytes(Text);
                    return Encoding.UTF8.GetString(mybyte);
                }
            }
            else
            {
                Debug.Log("Error:[" + filePath + "]该文件不存在！");
                return null;
            }
        }
        catch (Exception)
        {
           
        }
        return null;
    }

    public static int GetFileLine(string filePath)
    {
        //文件路径

        try
        {
            if (File.Exists(filePath))
            {
                using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
                {
                    int lineCount = 0;
                    while (sr.Peek() >= 0)
                    {
                        sr.ReadLine();
                        lineCount+=1;
                    }
                    return lineCount;
                }
            }
            else
            {
                Debug.Log("Error:[" + filePath + "]该文件不存在！");
                return 0;
            }
        }
        catch (Exception)
        {

        }
        return 0;
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="filePath">文件路径</param>
    public static void DeleteFile(string filePath)
    {
        if(File.Exists(filePath))
        {
            File.Delete(filePath);
        }
    }

    /// <summary>
    /// 拷贝文件夹
    /// </summary>
    /// <param name="sourceDirectory">源目录</param>
    /// <param name="destDirectory">目标目录</param>
    public static void CopyDirectory(string sourceDirectory, string destDirectory)
    {
        //判断源目录和目标目录是否存在，如果不存在，则创建一个目录            
        if (!Directory.Exists(sourceDirectory))
        {
            Directory.CreateDirectory(sourceDirectory);
        }
        if (!Directory.Exists(destDirectory))
        {
            Directory.CreateDirectory(destDirectory);
        }
        //拷贝文件            
        CopyFile(sourceDirectory, destDirectory);
        //拷贝子目录                   
        //获取所有子目录名称            
        string[] directionName = Directory.GetDirectories(sourceDirectory);
        foreach (string directionPath in directionName)
        {
            //根据每个子目录名称生成对应的目标子目录名称                
            string directionPathTemp = Path.Combine(destDirectory, directionPath.Substring(sourceDirectory.Length + 1));// 
            //destDirectory + "\\" + directionPath.Substring(sourceDirectory.Length + 1);
            //递归下去               
            CopyDirectory(directionPath, directionPathTemp);
        }
    }


    /// <summary>
    /// 拷贝文件
    /// </summary>
    /// <param name="sourceDirectory">源文件</param>
    /// <param name="destDirectory">目标文件</param>
    public static void CopyFile(string sourceDirectory, string destDirectory)
    {
        //获取所有文件名称            
        string[] fileName = Directory.GetFiles(sourceDirectory);
        foreach (string filePath in fileName)
        {
            //根据每个文件名称生成对应的目标文件名称                
            string filePathTemp = Path.Combine(destDirectory, filePath.Substring(sourceDirectory.Length + 1));// destDirectory + "\\" + filePath.Substring(sourceDirectory.Length + 1);     
                                                                                                              //若不存在，直接复制文件；若存在，覆盖复制                
            if (File.Exists(filePathTemp))
            {
                File.Copy(filePath, filePathTemp, true);
            }
            else
            {
                File.Copy(filePath, filePathTemp);
            }
        }
    }

    /// <summary>
    /// 判断两个文件内容是否相同
    /// </summary>
    /// <param name="filePath1">文件一路径</param>
    /// <param name="filePath2">文件二路径</param>
    /// <returns></returns>
    public static bool isValidFileContent(string filePath1, string filePath2)
    {
        //创建一个哈希算法对象 
        using (HashAlgorithm hash = HashAlgorithm.Create())
        {
            using (FileStream file1 = new FileStream(filePath1, FileMode.Open), file2 = new FileStream(filePath2, FileMode.Open))
            {


                //int fsLen = (int)file1.Length;
                //byte[] heByte = new byte[fsLen];
                //int r = file1.Read(heByte, 0, heByte.Length);
                //string myStr = System.Text.Encoding.UTF8.GetString(heByte,0,r);
                //myStr.Replace("_Backup", "");
                //byte[] byteArray = System.Text.Encoding.Default.GetBytes(myStr);

                //byte[] hashByte1 = hash.ComputeHash(byteArray);//哈希算法根据文本得到哈希码的字节数组 
                //fsLen = (int)file2.Length;
                //heByte = new byte[fsLen];
                //r = file2.Read(heByte, 0, heByte.Length);
                //string myStr2 = System.Text.Encoding.UTF8.GetString(heByte, 0, r);

                //byteArray = System.Text.Encoding.Default.GetBytes(myStr2);
                //Debug.Log(myStr== myStr2);
                //byte[] hashByte2 = hash.ComputeHash(byteArray);
                byte[] hashByte1 = hash.ComputeHash(file1);//哈希算法根据文本得到哈希码的字节数组 
                byte[] hashByte2 = hash.ComputeHash(file2);
                string str1 = BitConverter.ToString(hashByte1);//将字节数组装换为字符串 
                string str2 = BitConverter.ToString(hashByte2);
                Debug.Log(str1 + "\n\t" + str2);
                return (str1 == str2);//比较哈希码 
            }
        }
    }



    /// <summary>
    /// 获取文件是否存在
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static bool GetFileSuccess(string filePath)
    {
        if (File.Exists(filePath))
        {
            return true;

        }
        else
        {

            return false;
        }
    }

    /// <summary>
    /// 依据指定的 Assets下的文件路径 返回这个路径下的全部文件名称//
    /// </summary>
    /// <returns>文件名称数组</returns>
    /// <param name="path">Assets下“一"级路径</param>
    /// <param name="pattern">筛选文件后缀名的条件.</param>
    /// <typeparam name="T">函数模板的类型名t</typeparam>
    public static List<string> GetObjectNameToArray(string path, string pattern,bool all=false)
    {
        string objPath = Application.dataPath + "/" + path;
       
        string[] directoryEntries;
        try
        {
            //返回指定的文件夹中文件和子文件夹的名称的数组或空数组
            directoryEntries = System.IO.Directory.GetFileSystemEntries(objPath);

            for (int i = 0; i < directoryEntries.Length; i++)
            {
                string p = directoryEntries[i];
                //得到要求文件夹下的文件或者文件夹（一级的）//
                //string[] tempPaths = StringExtention.SplitWithString(p, "/Assets/" + path + "\\");
                string[] tempPaths = p.SplitWithString("/Assets/" + path + "\\");
                //tempPaths 切割后的不可能为空,仅仅要directoryEntries不为空//
                if (tempPaths[1].EndsWith(".meta"))
                    continue;
                string[] pathSplit = tempPaths[1].SplitWithString(".");
                //文件
                if (pathSplit.Length > 1)
                {

                    nameArray.Add(all? p.Replace(Application.dataPath+ "/Resources/","").Replace("\\","/") : pathSplit[0]);
                }
                //遍历子目录下 递归吧！
                else
                {
                    GetObjectNameToArray(path + "/" + pathSplit[0], "pattern",all);
                    continue;
                }
            }
        }
        catch (System.IO.DirectoryNotFoundException)
        {
            Debug.Log("The path encapsulated in the " + objPath + "Directory object does not exist.");
        }
        return nameArray;
    }


    


}
